Interpolation Search Algorithm
The Interpolation Search Algorithm is an advanced search technique that aims to find a specific element within an ordered list or array. This algorithm is particularly useful when the data is uniformly distributed, as it estimates the position of the target value in the list, allowing for a more efficient search process compared to other search algorithms like binary search. Interpolation search relies on the idea that given a set of data, one can predict the location of the target value by using the numerical relationship between the values in the data set.
The algorithm starts by calculating the probable position of the target value in the list using a formula that takes into account the lowest value, highest value, and the target value. This estimated position is then used to narrow down the search range, further refining the position of the target value. The process continues until the target value is found or the search range becomes empty, meaning the target value is not present in the list. Due to its ability to estimate the position of the target value, interpolation search can achieve significantly better performance than binary search, especially for large and uniformly distributed data sets. However, when the data is not uniformly distributed, the performance of the algorithm can deteriorate, becoming less efficient than other search methods.
#include <iostream>
int InterpolationSearch(int A[], int n, int x)
{
int low = 0;
int high = n - 1;
while (low <= high)
{
int mid = low + (((high - 1) * (x - A[low])) / (A[high] - A[low]));
if (x == A[mid])
return mid; // Found x, return (exit)
else if (x < A[mid])
high = mid - 1; // X lies before mid
else
low = mid + 1; // x lies after mid
}
return -1;
}
int main()
{
int A[] = {2, 4, 5, 7, 13, 14, 15, 23};
int x = 17;
int index = InterpolationSearch(A, 8, x); // passed array A inside the InterpolationSearch function
if (index != -1)
std::cout << "Number " << x << " is at " << index;
else
std::cout << "Number " << x << " not found";
}
// randomly set x bcoz array was defined by us , therefore not reasonable for asking input.
// We could have asked for input if array elements were inputed by the user.